package com.nulldev.util.networking.npacket4.manager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.nulldev.util.data.Variables;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.networking.npacket4.nPacket;

public class PacketManager {

	private final Map<String, PacketListener> listeners = new ConcurrentHashMap<String, PacketListener>();
	private final static Logger log = LoggerFactory.getLogger();

	public PacketManager() {
	}

	public PacketManager(final PacketListener[] listeners) {
		for (final PacketListener listener : listeners) {
			this.register(listener);
		}
	}

	public void register(final PacketListener listener) {
		Variables.notNullE(listener);
		Variables.notNullE(listener.listenFor());
		this.listeners.put(listener.listenFor(), listener);
	}

	public void packet(final nPacket packet) {
		Variables.notNullE(packet);
		final String id = packet.getPacketID();
		final PacketListener pl = listeners.get(id);
		if (pl != null) {
			pl.onPacket(packet);
		} else {
			log.warn("Unknown packet: " + id);
		}
	}
}
